$(function(){
    var wenda_tags_box=$("#wenda_tags_box");
    if(typeof(wenda_tags_box[0])!="undefined"){
        $("body").delegate("#wenda_tags_box a","click",function(){
           $(this).hasClass('on') ? $(this).removeClass('on') : $(this).addClass('on');
           check_wenda_tags(wenda_tags_box);
        });
    }
    $("#seach_wenda_key_tag").keyup(function(e){
        if(e.keyCode == 38 || e.keyCode == 40){
            select_tag(e.keyCode);
            return;
        }else if(e.keyCode == 13){
            if(($("#seach_wenda_tag_box a.active"))[0] !== undefined){
                selected_tag($("#seach_wenda_tag_box a.active"));
                return;
            }
        }
        var _self=$(this),_key_tag=_self.val(),_seach_wenda_tag_box=$("#seach_wenda_tag_box");
        if(_key_tag == "") {_seach_wenda_tag_box.css("display","none");return;};
        _seach_wenda_tag_box.css("display","block").html("<span class='load-tag'></span>");
        doGetRequest("/ajax/seach_wenda_tag",{tag_key:_key_tag},true,function(res){
            var html = res.seachRes;
            if(html == ""){
                _seach_wenda_tag_box.html("<span class='empty'>匹配为空</span>");
            }else{
                setTimeout(function(){
                    _seach_wenda_tag_box.html("").html(html);
                },500);
            }
        },function(res){});
    });
    $("body").delegate("#seach_wenda_tag_box a","click",function(e){
        selected_tag($(this));
    });
    
    function check_wenda_tags(obj){
        if((obj.find("a[class='on']")).length > 5){
            $("#wenda_tags_error").css("display","block");
        }else{
            $("#wenda_tags_error").css("display","none");
        }
    }
    function check_wenda_is_on(obj){
        var t=0;
        var tt=setInterval(function(){
            t++;
            $(obj).hasClass('on') ? $(obj).removeClass('on') : $(obj).addClass('on');
            if(t == 4) {clearInterval(tt);}
        },300);
        return;
    }
    
    var _wenda_titile_obj=$("#wenda_title"),_wenda_content_obj=$("#wenda_content"),_wenda_tags_obj=$("#wenda_tags_box"),
    _email_notice_checkbox=$("#email_notice_select"),_T_wenda_publish_btn=$("._T_wenda_publish");
    _T_wenda_publish_btn.on("click",function(){
        var _self=$(this),_title=$.trim(_wenda_titile_obj.val()),_content=$(".wenda-editor").html(),_tags=check_tags(_wenda_tags_obj),is_email=_email_notice_checkbox.hasClass("active") ? 1 : 0,
        params={},_unvalid=_self.attr("data-unvalid"),_url=_self.attr("data-action-url");
        if(!check_title(_title)){return;};
        if(!_tags){layer.msg("至少选择一个问题标签哦",{icon:0,time:2000,shift:6,offset:300});return;}
        params.wendaTitle=_title,params.wendaContent=_content,params.wendaTag=_tags,params.is_email=is_email,params.timestamp=Math.random();
        _self.attr("disabled","disabled").css("cursor","not-allowed").val(_unvalid);
        doRequest(_url,params,true,function(data){
            layer.confirm(data.errorMsg, {shift:6,offset:300,closeBtn:0,
                btn: ['前去查看','继续发布'],icon:6,title:"小6提示" //按钮
                }, function(){
                    window.location.href = data.url;
                }, function(){
                    window.location.reload();
            });
        },function(data){
            _self.removeAttr("disabled").css("cursor","pointer").val("发布问题");
            layer.msg(data.errorMsg,{icon:0,time:2000,offset:300});
        });
    });
    _wenda_titile_obj.keyup(function(){
        var _self=$(this),_title=$.trim(_self.val());
        _total_len=check_str_len(_title);
        $(".title-count").text(_total_len);
    });
    
    $(".wenda-editor").on("paste",function(e){
        var _self = $(e.currentTarget);
        setTimeout(function(){
            var str = _self.html();
            str = str.replace(/style=\".*?\"/ig,"");
            str = str.replace(/id=[\'|\"].*[\'|\"]/ig,"");
            str = str.replace(/class=[\'|\"].*[\'|\"]/ig,"");
            _self.html(str);
            
            var img = _self.find("img");
            img.each(function(){
                var src=$(this).attr("src");
                (src.indexOf("tan66")) < 0 ? $(this).replaceWith("") : $(this).before("<br>");
            });
        },10);
    }).on("blur",function(e){
        var _self=$(e.currentTarget);
        if($.trim(_self.text()) === ""){
            _self.siblings(".editor-placeholder").show();
        }
    }).on("keyup",function(e){
        var _self=$(e.currentTarget),_content=_self.html();
        var _len=check_str_len($.trim(_content.replace(/<\/?[^>]*>/g,'')));
        $(".content-count").text(_len);
    }).on("keypress",function(e){
        var ev = document.all ? window.event : e;
        if(ev.keyCode==13 && document.queryCommandSupported && document.queryCommandSupported("insertHTML")) {
            document.execCommand("insertHTML", false, "<br><br>");
            return false;
        }
        return true;
    });
    function check_tags(obj){
        var str="",obj = obj.find("a[class='on']");
        if(typeof(obj[0]) && obj.length > 0){
           obj.each(function(index,data){
               if((index+1) < 6){
                   str += $(this).attr("data-name")+"_"+$(this).attr("data-tid")+",";
               }
           });
           return str.substring(0,str.length-1);
        }else{
            return "";
        }
        
    }
    function check_title(str){
        var total_len,ch_len,en_len;
        if(str == ""){layer.msg("请输入问答标题",{icon:0,time:2000,shift:6,offset:300});return false;}
        total_len=str.length,en_len=(str.replace(/[\u4E00-\u9FA5]/g,"")).length,ch_len=total_len-en_len,en_len=parseInt(en_len/2);
        if((ch_len+en_len) < 5){layer.msg("标题不能<span style='font-size:16px;color:#e66d61;'>小于5个字</span>哦",{icon:0,time:2000,shift:6,offset:300});return false;}
        return true;
    }
    
    function select_tag(code){
        $("#seach_wenda_tag_box").focus();
        var tar = $("#seach_wenda_tag_box a");
        if(tar[0] === undefined){return;}
        index = $("#seach_wenda_tag_box a.active").index();
        num = 0;
        if(code == 38){
            if(index < 1){return}
            num = index - 1;
        }else if(code == 40){
            if((index + 1) == tar.length){return;}
            num = index + 1;
        }
        var obj = tar.eq(num);
        obj.addClass("active").siblings().removeClass("active");
        $("#seach_wenda_tag_box").scrollTop(obj[0].scrollHeight * num);
    }
    
    function selected_tag(obj){
        var _self=obj,_flag=$("#wenda_tags_box").find("a[data-tid="+_self.attr("seach-tid")+"]");
        $("#seach_wenda_tag_box").html("").hide();$("#seach_wenda_key_tag").val("");
        if(typeof(_flag[0]) != "undefined"){
            if(_flag.hasClass("on")){
                check_wenda_is_on(_flag);
            }else{
                _flag.addClass("on");
            }
        }else{
            $("#wenda_tags_box").append("<a href='javascript:void(0);' data-name='"+_self.attr("seach-name")+"' data-tid='"+_self.attr("seach-tid")+"' class='on'>"+_self.attr("seach-name")+"</a>");
        }
        check_wenda_tags($("#wenda_tags_box"));
    }
});
